package com.xiaohua.api.config;

import com.alibaba.fastjson.JSONObject;
import com.xiaohua.api.common.constants.TextInConstants;
import com.xiaohua.api.common.properties.TextInProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * TextIn客户端配置类
 * 在应用启动时验证TextIn API凭证和连接状态
 *
 * @author 小花
 * @date 2025-04-01
 */
@Component
public class TextInClientConfig implements CommandLineRunner {

    private static final Logger log = LoggerFactory.getLogger(TextInClientConfig.class);

    @Autowired
    private TextInProperties textInProperties;

    @Override
    public void run(String... args) throws Exception {
        // 在应用启动时验证TextIn API凭证
        verifyTextInApiCredentials();
    }

    /**
     * 验证TextIn API凭证和连接状态
     */
    private void verifyTextInApiCredentials() {
        try {
            log.info("验证TextIn API凭证和连接状态");
            
            // 获取API凭证
            String appId = textInProperties.getAppId();
            String secretCode = textInProperties.getSecretCode();
            
            if (appId == null || secretCode == null) {
                log.error("TextIn API凭证未正确加载，AppId或SecretCode为空");
                return;
            }
            
            log.info("检查TextIn API凭证，使用AppId：{}", maskString(appId));
            
            // 验证API连接，使用证件分类API做简单测试
            testTextInApiConnection(appId, secretCode);
            
        } catch (Exception e) {
            log.error("验证TextIn API凭证出错: {}", e.getMessage(), e);
        }
    }
    
    /**
     * 测试TextIn API连接
     */
    private void testTextInApiConnection(String appId, String secretCode) {
        try {
            // 使用简单的健康检查URL（此处使用证件分类API作为示例）
            String testUrl = TextInConstants.API_URL_CERT_CLASSIFY;
            
            log.info("测试TextIn API连接: {}", testUrl);
            
            // 创建URL并打开连接
            URL url = new URL(testUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            
            // 设置请求方法和超时
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(TextInConstants.CONNECTION_TIMEOUT);
            conn.setReadTimeout(TextInConstants.READ_TIMEOUT);
            
            // 设置HTTP头
            conn.setRequestProperty("Content-Type", "application/json");
            
            // 启用输入输出流
            conn.setDoOutput(true);
            conn.setDoInput(true);
            
            // 创建请求体
            JSONObject requestBody = new JSONObject();
            requestBody.put("app_id", appId);
            requestBody.put("time_stamp", System.currentTimeMillis() / 1000);
            
            // 发送请求
            try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) {
                out.write(requestBody.toString().getBytes("UTF-8"));
                out.flush();
            }
            
            // 获取响应
            int responseCode = conn.getResponseCode();
            
            if (responseCode == HttpURLConnection.HTTP_OK) {
                log.info("TextIn API连接测试成功，服务可用");
            } else {
                log.warn("TextIn API连接测试失败，HTTP状态码: {}", responseCode);
                
                // 读取错误响应内容
                try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getErrorStream()))) {
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = in.readLine()) != null) {
                        response.append(line);
                    }
                    log.warn("错误响应: {}", response.toString());
                }
            }
            
        } catch (IOException e) {
            log.error("测试TextIn API连接失败: {}", e.getMessage(), e);
        }
    }
    
    /**
     * 掩码显示字符串，仅显示前几个字符
     */
    private String maskString(String input) {
        if (input == null || input.length() <= 4) {
            return input;
        }
        return input.substring(0, Math.min(4, input.length())) + "********";
    }
} 